package com.zhixin.fans.ks.ui.charge;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.zhixin.fans.ks.KeyConstant;
import com.zhixin.fans.ks.R;
import com.zhixin.fans.ks.api.CommonApi;
import com.zhixin.fans.ks.api.res.GoodOption;
import com.zhixin.fans.ks.api.res.SubModule;
import com.zhixin.fans.ks.api.res.UserInfo;
import com.zhixin.fans.ks.api.res.UserInfoRes;
import com.zhixin.fans.ks.manager.UserInfoManager;
import com.zhixin.fans.ks.ui.base.BaseNeedLoginActivity;
import com.zhixin.fans.ks.ui.history.OrderRecordActivity;

import org.eenie.common.subscribes.ProgressSubscriber;
import org.eenie.common.views.TopBarLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;


public class ModuleGoodActivity extends BaseNeedLoginActivity implements Observer<UserInfo> {
    public static final String ROUTE_PATH = "/charge/module_goods";

//    CoupleApi mCoupleApi;

    CommonApi mCommonApi;


    SubModule mSubModule;
    @BindView(R.id.top_bar)
    TopBarLayout mTopBar;
    @BindView(R.id.img_user_header)
    QMUIRadiusImageView mImgUserHeader;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.tv_user_id)
    TextView mTvUserId;
    @BindView(R.id.tv_fb_count)
    TextView mTvFbCount;
    @BindView(R.id.btn_buy_fb)
    QMUIRoundButton mBtnBuyFb;
    @BindView(R.id.edit_account)
    EditText mEditAccount;
    @BindView(R.id.rv_coin_option)
    RecyclerView mRvCoinOption;
    @BindView(R.id.tv_pay_money)
    TextView mTvPayMoney;
    @BindView(R.id.btn_submit)
    Button mBtnSubmit;


    UserInfoManager mUserInfoManager;

    ModuleOptionAdapter mModuleOptionAdapter;

    List<GoodOption> mGoods = new ArrayList<>();

    GoodOption mGoodOption;

    @Override
    public int initContentView() {
        return R.layout.activity_module_good;
    }

    @Override
    public void initInjector() {
        mCommonApi = getApplicationComponent().getApiManager().create(CommonApi.class);
        mCommonApi.bindLife(lifecycleSubject);

        mSubModule = JSON.parseObject(getIntent().getStringExtra(KeyConstant.KEY_SUB_MODULE), SubModule.class);
        mUserInfoManager = getCoupleAppComponent().getUserInfoManager();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);


        mUserInfoManager.observe(this, this);
        mUserInfoManager.update();

        mTopBar.setTitle(mSubModule.getGca_name());
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mEditAccount.setHint(mSubModule.getGca_desc());

        mRvCoinOption.setLayoutManager(new GridLayoutManager(mContext, 3));
        mRvCoinOption.setAdapter(mModuleOptionAdapter = new ModuleOptionAdapter(mGoods) {
            @Override
            public void onItemSelected(GoodOption option) {
                mGoodOption = option;
                mTvPayMoney.setText(String.format("支付金额：￥%s", option.getG_price()));
            }
        });
        fetchModuleGoods(mSubModule);
    }


    private void fetchModuleGoods(SubModule module) {
        mCommonApi.fetchModuleGoods(module.getGca_id())
                .compose(bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .subscribe(new ProgressSubscriber<List<GoodOption>>() {
                    @Override
                    public void onNext(List<GoodOption> goodOptions) {
                        mGoods.clear();
                        mGoods.addAll(goodOptions);
                        mModuleOptionAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    @OnClick(R.id.btn_submit)
    public void submitOrder() {
        if (mGoodOption != null) {
            if (!TextUtils.isEmpty(mEditAccount.getText())) {
                mCommonApi.submitOrder( mEditAccount.getText().toString(), mGoodOption.getG_id())
                        .subscribe(new ProgressSubscriber<String>(mContext, "提交订单...") {
                            @Override
                            public void onNext(String loginEntity) {
                                ToastUtils.showShort("购买成功，耐心等待系统处理");
                                fetchUserInfo();
                            }

                            @Override
                            public void onFinish() {

                            }


                            @Override
                            public void handleError(Throwable e) {
                                super.handleError(e);

                                startActivity(new Intent(mContext, ChargeCoinActivity.class));

                            }
                        });
            } else {
                ToastUtils.showShort("请填写备注信息");
            }
        } else {
            ToastUtils.showShort("请选择要充值的项目");
        }


    }


    @Override
    public void onChanged(UserInfo userInfo) {
        if (userInfo != null && userInfo.getU_id() > 0) {
            Glide.with(mContext).asBitmap().load(userInfo.getU_headPicture()).into(mImgUserHeader);
            mTvUserName.setText(userInfo.getU_nickName());
            mTvUserId.setText(String.format("ID：%s", userInfo.getU_id()));
            mTvFbCount.setText(String.format("粉币：%s", userInfo.getU_usermoney()));
        } else {
            Glide.with(mContext).asBitmap().load(R.mipmap.ic_model_qq).into(mImgUserHeader);
            mTvUserName.setText("未登录");
            mTvUserId.setText("-------");
        }
    }


    @OnClick(R.id.btn_buy_fb)
    public void onViewClicked() {
        startActivity(new Intent(mContext, ChargeCoinActivity.class));
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
//            submitOrder();
//        }
//    }


    private void fetchUserInfo() {
        mCommonApi.fetchUserInfo("")
                .subscribe(new ProgressSubscriber<UserInfoRes>(mContext) {
                    @Override
                    public void onNext(UserInfoRes userInfoRes) {
                        mUserInfoManager.setValue(userInfoRes.getUserInfo());
                        setResult(Activity.RESULT_OK);
                        startActivity(new Intent(mContext, OrderRecordActivity.class));
                        finish();
                    }

                    @Override
                    public void onFinish() {


                    }
                });
    }


}
